/*
 * @Description: 地球自转效果
 * @Version: 1.0
 * @Author: Julian
 * @Date: 2022-02-25 15:14:20
 * @LastEditors: Julian
 * @LastEditTime: 2022-02-26 12:18:03
 */

import * as Cesium from "cesium";

/**
 * @description: 地球自转类
 */
class GlobeRotate {
    constructor(viewer, speed = 15) {
        this._viewer = viewer;
        this._speed = speed; // 默认速度为15
    }

    // 根据国际天体参考系计算旋转矩阵
    _icrf() {
        if (this._viewer.scene.mode !== Cesium.SceneMode.SCENE3D) {
            return ture;
        }
        let icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(this._viewer.clock.currentTime);
        if (icrfToFixed) {
            let camera = this._viewer.camera;
            let offset = Cesium.Cartesian3.clone(camera.position);
            let transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
            // 偏移相机，否则会场景旋转而地球不转
            camera.lookAtTransform(transform, offset);
        }
    }

    // 绑定事件
    _bindEvent() {
        // 转速 = 设定速度值 * 1000
        this._viewer.clock.multiplier = this._speed * 1000;
        this._viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
        this._viewer.scene.postUpdate.addEventListener(this._icrf, this);
    }

    // 解除绑定
    _unbindEvent() {
        this._viewer.clock.multiplier = 1;
        this._viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
        this._viewer.scene.postUpdate.removeEventListener(this._icrf, this);
    }

    // 开始旋转
    start() {
        this._viewer.clock.shouldAnimate = true;
        this._unbindEvent();
        this._bindEvent();
        return this;
    }

    // 停止旋转
    stop() {
        this._unbindEvent();
        return this;
    }

    // 添加设置速度的方法
    setSpeed(speed) {
        this._speed = speed;
        if (this._viewer.clock.multiplier !== 1) {  // 如果当前正在旋转
            this._viewer.clock.multiplier = this._speed * 1000;
        }
        return this;
    }
}

export default GlobeRotate;